/**
 * 工程名称:oms
 * 文件名称:StockPushServiceImpl.java
 * 所属包:cn.rkylin.oms.system.stockpush.service.impl
 * 创建时间:2017年9月4日下午2:45:59
 * Copyright (c) 2017 瑞金麟(大连)信息技术有限公司 All Rights Reserved.
 * 创建人:zhanghao
 */

package cn.rkylin.oms.system.stockpush.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.ApolloMap;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.ectrade.service.IEcTradeService;
import cn.rkylin.oms.goods.domain.SkuStock;
import cn.rkylin.oms.goods.service.IGoodsService;
import cn.rkylin.oms.goods.vo.PrjSkuVO;
import cn.rkylin.oms.goods.vo.SkuStockVO;
import cn.rkylin.oms.item.service.IItemService;
import cn.rkylin.oms.item.vo.SkuVO;
import cn.rkylin.oms.system.project.vo.ProjectVO;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.service.IShopStorService;
import cn.rkylin.oms.system.shop.vo.ShopStorVO;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.system.stockpush.dao.IStockFmlaDAO;
import cn.rkylin.oms.system.stockpush.dao.IStockFmlaRatioSkuDAO;
import cn.rkylin.oms.system.stockpush.dao.IStockFmlaRatioStorageDAO;
import cn.rkylin.oms.system.stockpush.domain.StockFmla;
import cn.rkylin.oms.system.stockpush.domain.StockFmlaRatioSku;
import cn.rkylin.oms.system.stockpush.domain.StockFmlaRatioStorage;
import cn.rkylin.oms.system.stockpush.service.IStockPushService;
import cn.rkylin.oms.system.stockpush.util.IStockCaculator;
import cn.rkylin.oms.system.stockpush.util.impl.FelBasedStockCaculator;
import cn.rkylin.oms.system.stockpush.vo.ProjectStockFmlaVO;
import cn.rkylin.oms.system.stockpush.vo.StockFmlaRatioSkuVO;
import cn.rkylin.oms.system.stockpush.vo.StockFmlaRatioStorageVO;
import cn.rkylin.oms.system.stockpush.vo.StockFmlaVO;
import cn.rkylin.oms.system.storage.service.IStorService;
import cn.rkylin.oms.system.storage.vo.StorVO;
import cn.rkylin.oms.warehouse.stock.service.IStockService;
import cn.rkylin.oms.warehouse.stock.vo.StockVO;

/**
 * 类名:StockPushServiceImpl <br/>
 * 作用: 库存推送设置服务实现类. <br/>
 * 创建原因: 库存推送设置服务的实现. <br/>
 * 创建时间: 2017年9月4日 下午2:45:59 <br/>
 * 
 * @author zhanghao
 * @version v1.0
 * @since JDK 1.6
 * @see
 */
@Service("stockPushService")
public class StockPushServiceImpl extends ApolloService implements IStockPushService {
    private static final Log logger = LogFactory.getLog(StockPushServiceImpl.class);
    /**
     * stockFmlaRatioStorageDAO:仓库推送比例数据访问层.
     * 
     * @since JDK 1.6
     */
    @Autowired
    IStockFmlaRatioStorageDAO stockFmlaRatioStorageDAO;
    /**
     * stockPushRatioSkuDAO:商品推送比例数据访问层.
     * 
     * @since JDK 1.6
     */
    @Autowired
    IStockFmlaRatioSkuDAO stockPushRatioSkuDAO;

    @Autowired
    IShopStorService shopStorService;
    /**
     * stockFmlaDAO:仓库公式计算数据访问层.
     * 
     * @since JDK 1.6
     */
    @Autowired
    IStockFmlaDAO stockFmlaDAO;
    /**
     * storService:仓库服务层.
     * 
     * @since JDK 1.6
     */
    @Autowired
    private IStorService storService;
    /**
     * stockService:仓库服务层.
     */
    @Autowired
    private IStockService stockService;

    /**
     * ecTradeService:平台交易服务层.
     */
    @Autowired
    IEcTradeService ecTradeService;
    /**
     * shopService:店铺服务层.
     * 
     * @since JDK 1.6
     */
    @Autowired
    private IShopService shopService;

    /**
     * itemService:平台商品服务层.
     * 
     * @since JDK 1.6
     */
    @Autowired
    private IItemService itemService;
    /**
     * itemService:系统商品服务层.
     * 
     * @since JDK 1.6
     */
    @Autowired
    private IGoodsService goodsService;

    /**
     * 方法复写 获取当前登录人可以设置推送比例的项目列表.包括： 1. 获取当前登录人可以访问的项目列表 2. 获取项目下的库存推送公式 3.
     * 计算项目下的库存推送设置情况 4. 计算项目下的商品推送设置情况
     * 
     * @throws Exception
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#getUserProjectWithStockFmla()
     */
    @Override
    public List<ProjectStockFmlaVO> getUserProjectWithStockFmla() throws Exception {
        List<ProjectStockFmlaVO> returnList = new ArrayList<ProjectStockFmlaVO>();
        Date lastUpdateTime = null;
        // 获取当前登录人的可访问项目
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        Map<String, ProjectVO> currentProjectMap = currentUser.getProjectMap();

        // 构造可访问项目的返回值列表
        Iterator<String> projectIterator = currentProjectMap.keySet().iterator();
        while (projectIterator.hasNext()) {
            lastUpdateTime = null;
            String projectId = projectIterator.next();
            String projectName = currentProjectMap.get(projectId).getPrjName();
            ProjectStockFmlaVO projectVO = new ProjectStockFmlaVO();
            projectVO.setProjectId(projectId);
            projectVO.setProjectName(projectName);
            projectVO.setOperation(StringUtils.EMPTY);

            // 获取项目的库存公式相关信息
            StockFmla stockFmla = getStockFmlaByProjectId(projectId);
            if (null != stockFmla) {
                lastUpdateTime = stockFmla.getUpdateTime();
            }
            if (stockFmla != null) {
                projectVO.setFmlaContent(stockFmla.getFormula());
                projectVO.setIsFmlaSet("y");
                projectVO.setStockType(stockFmla.getStockValMode());
            }

            /*
             * 获取项目的库存推送比例相关信息: 如果该项目的该仓库设置过，就表示设置过 推送比例即：已经设置过的仓库／总仓库数
             * 
             */
            List<StorVO> storeList = storService.findByProjectId(projectId);
            long totalStoreLength = storeList.size();

            StockFmlaRatioStorageVO stockFmlaRatioStorageVO = new StockFmlaRatioStorageVO();
            stockFmlaRatioStorageVO.setPrjId(projectId);
            List<StockFmlaRatioStorage> storageRatioList = getStockFmlaRatioStorageList(stockFmlaRatioStorageVO);

            List<String> noRepeatStoreList = new ArrayList<String>();
            Date lastUpdateTime_storage = null;
            for (StockFmlaRatioStorage stockFmlaRatioStorage : storageRatioList) {
                if (null == lastUpdateTime_storage || lastUpdateTime_storage.before(stockFmlaRatioStorage.getUpdateTime())) {
                    lastUpdateTime_storage = stockFmlaRatioStorage.getUpdateTime();
                }
                if (!noRepeatStoreList.contains(stockFmlaRatioStorage.getStorId())) {
                    noRepeatStoreList.add(stockFmlaRatioStorage.getStorId());
                }
            }

            long availabeStoreLength = noRepeatStoreList.size();
            projectVO.setFmlaRatioStorageContent(availabeStoreLength + "/" + totalStoreLength);

            /*
             * 判断逻辑：两种情况下会将最新时间赋值为仓库推送比例的最新更新时间：
             * 
             * 1. 仓库库存公式更新时间为空
             * 
             * 2. 仓库库存更新时间不为空，仓库推送比例最新更新时间也不为空，且后者早于前者
             * 
             * 否则，最新更新时间就赋值为仓库库存公式更新时间
             */

            if (lastUpdateTime != null && lastUpdateTime_storage != null && lastUpdateTime.before(lastUpdateTime_storage)
                    || lastUpdateTime == null) {
                lastUpdateTime = lastUpdateTime_storage;
            }

            /*
             * 如果项目下该商品有比例，就表示推送过： 推送比例即设置过推送的商品／商品总数
             */
            Map<String, Object> param = new ApolloMap<String, Object>();
            param.put("prjId", projectId);
            List<PrjSkuVO> resultList = itemService.getProjectSkuList(param);
            long totalSkuLength = resultList.size();

            StockFmlaRatioSkuVO stockFmlaRatioSkuVO = new StockFmlaRatioSkuVO();
            stockFmlaRatioSkuVO.setPrjId(projectId);
            List<StockFmlaRatioSkuVO> skuRatioList = getStockFmlaRatioSkuList(stockFmlaRatioSkuVO);
            List<String> noRepeatSkuList = new ArrayList<String>();

            Date lastUpdateTime_sku = null;
            for (StockFmlaRatioSkuVO stockFmlaRatioSkuVO2 : skuRatioList) {
                if (null == lastUpdateTime_sku || lastUpdateTime_sku.before(stockFmlaRatioSkuVO2.getUpdateTime())) {
                    lastUpdateTime_sku = stockFmlaRatioSkuVO2.getUpdateTime();
                }
                if (!noRepeatSkuList.contains(stockFmlaRatioSkuVO2.getSkuId())) {
                    noRepeatSkuList.add(stockFmlaRatioSkuVO2.getSkuId());
                }
            }
            long availableSkuLength = noRepeatSkuList.size();
            projectVO.setFmlaRatioSkuContent(availableSkuLength + "/" + totalSkuLength);

            /*
             * 计算逻辑类似于上面的逻辑
             * 
             * 判断逻辑：两种情况下会将最新时间赋值为商品推送比例的最新更新时间：
             * 
             * 1. 前置更新时间（仓库推送公式和仓库推送比例时间的较早者）为空
             * 
             * 2. 前置更新时间不为空，商品推送比例最新更新时间也不为空，且后者早于前者
             * 
             * 否则，最新更新时间就赋值为前置更新时间
             */
            if (null != lastUpdateTime && null != lastUpdateTime_sku && lastUpdateTime.before(lastUpdateTime_sku) || lastUpdateTime == null) {
                lastUpdateTime = lastUpdateTime_sku;
            }

            /*
             * 设置最近更新时间
             */
            if (null != lastUpdateTime) {
                projectVO.setUpdateTime(lastUpdateTime);
            }
            returnList.add(projectVO);
        }

        return returnList;
    }

    /**
     * 方法复写 根据查询条件获取仓库推送比例列表.
     * 
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#getStockFmlaRatioStorageList(cn.rkylin.oms.system.stockpush.vo.StockFmlaRatioStorageVO)
     */
    @Override
    public List<StockFmlaRatioStorage> getStockFmlaRatioStorageList(StockFmlaRatioStorageVO stockFmlaRatioStorageVO) throws Exception {
        return stockFmlaRatioStorageDAO.selectBySelectiveValue(stockFmlaRatioStorageVO);
    }

    /**
     * 方法复写 批量添加仓库推送比例.
     * 
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#saveStorageRatio(java.util.List)
     */
    @Override
    @Transactional
    public int saveStorageRatio(List<StockFmlaRatioStorageVO> storageRatioList) throws Exception {
        int returnValue = 0;
        Date now = new Date();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        for (StockFmlaRatioStorageVO stockFmlaRatioStorageVO : storageRatioList) {
            StockFmlaRatioStorage record = new StockFmlaRatioStorage();
            BeanUtils.copyProperties(stockFmlaRatioStorageVO,record);
            if ("y".equalsIgnoreCase(stockFmlaRatioStorageVO.getIsUpdate())) {
                // 如果推送比例是0，就需要删除这条数据
                record.setUpdateTime(now);
                if (stockFmlaRatioStorageVO.getRatio().intValue() == 0) {
                    record.setDeleted("y");
                }
                returnValue = stockFmlaRatioStorageDAO.updateByPrimaryKeySelective(record);
            } else {
                String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
                // 新增记录
                record.setCreateTime(now);
                record.setUpdateTime(now);
                record.setDeleted("n");
                String key = (String) currentUser.getEnterpriseMap().keySet().toArray()[0];
                record.setEntId(key);
                record.setRatioId(uuid);
                // 只有不为0的数据才能插入表格
                if (record.getRatio().intValue() != 0) {
                    returnValue = stockFmlaRatioStorageDAO.insert(record);
                }
            }
        }
        return returnValue;
    }

    /**
     * 方法复写 根据项目ID获取库存公式列表. 通常情况下，一个项目下只有一个库存计算公式
     * 
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#getStockFmlaByProjectId(java.lang.String)
     */
    @Override
    public StockFmla getStockFmlaByProjectId(String projectId) throws Exception {
        StockFmla stockFmla = null;
        StockFmlaVO stockFmlaVO = new StockFmlaVO();
        stockFmlaVO.setPrjId(projectId);
        stockFmlaVO.setDeleted("n");
        List<StockFmla> stockFmlaList = stockFmlaDAO.selectBySelectiveValue(stockFmlaVO);
        if (stockFmlaList.size() > 0) {
            stockFmla = stockFmlaList.get(0);
        }
        return stockFmla;
    }

    /**
     * 方法复写 保存库存公式： 如果库存公式存在，则更新数据。 如果库存公式不存在，则新增数据。 .
     * 
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#saveStockFmla(cn.rkylin.oms.system.stockpush.domain.StockFmla)
     */
    @Override
    @Transactional
    public StockFmla saveStockFmla(StockFmla stockFmlaVO) throws Exception {
        int returnValue = 0;
        Date now = new Date();
        StockFmla stockFmla = new StockFmla();

        BeanUtils.copyProperties(stockFmlaVO,stockFmla);

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (!StringUtils.isNotEmpty(stockFmlaVO.getFmlaId())) {
            String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
            // 新增记录
            stockFmla.setCreateTime(now);
            stockFmla.setCreateUserId(currentUser.getId());
            stockFmla.setCreateUserName(currentUser.getFullName());
            stockFmla.setUpdateTime(now);
            stockFmla.setUpdateUserId(currentUser.getId());
            stockFmla.setUpdateUserName(currentUser.getFullName());
            stockFmla.setDeleted("n");
            String key = (String) currentUser.getEnterpriseMap().keySet().toArray()[0];
            stockFmla.setEntId(key);
            stockFmla.setFmlaId(uuid);

            // 在传递数据时，如果项目名称为空，则需要根据项目ID把项目名称取到，取自用户信息
            if (StringUtils.isEmpty(stockFmla.getPrjName())) {
                stockFmla.setPrjName(currentUser.getProjectMap().get(stockFmlaVO.getPrjId()).getPrjName());
            }
            // 只新增非空的数据
            if (StringUtils.isNotEmpty(stockFmla.getFormula())) {
                returnValue = stockFmlaDAO.insert(stockFmla);
            }
        } else {
            // 更新记录
            stockFmla.setUpdateTime(now);
            stockFmla.setCreateUserId(currentUser.getId());
            stockFmla.setCreateUserName(currentUser.getFullName());

            // 在传递数据时，如果项目名称为空，则需要根据项目ID把项目名称取到，取自用户信息
            if (StringUtils.isEmpty(stockFmla.getPrjName())) {
                stockFmla.setPrjName(currentUser.getProjectMap().get(stockFmlaVO.getPrjId()).getPrjName());
            }
            if (StringUtils.isNotEmpty(stockFmla.getFormula())) {
                returnValue = stockFmlaDAO.updateByPrimaryKeySelective(stockFmla);
            } else {
                stockFmla.setDeleted("y");
                returnValue = stockFmlaDAO.updateByPrimaryKeySelective(stockFmla);
            }
        }
        return stockFmla;
    }

    /**
     * getPushAllowed:查询某商品Sku推送的有效性. <br/>
     *
     * @author zhanghao
     * @param shopId
     *            平台店铺ID
     * @param ecSkuId
     *            平台商品规格编码
     * @param storageId
     *            仓库ID
     * @return 如果不进行同步，则返回值为0；如果进行同步，则返回值为“success”
     * @throws Exception
     * @since JDK 1.6
     */
    private String getPushAllowed(String shopId, String ecSkuId, String storageId) throws Exception {
        String returnMessage = "success";
        // 判断店铺库存同步是否开启
        ShopVO shop = shopService.getShopById(shopId);
        String isSyncInventory = shop.getIsSyncInventory();
        if (null == isSyncInventory || "n".equals(isSyncInventory)) {
            logger.info("店铺[" + shop.getShopName() + "]库存同步已关闭");
            returnMessage = "店铺[\"+shop.getShopName()+\"]库存同步已关闭";
        } else {
            // 判断商品的库存同步是否开始
            SkuVO skuVO = new SkuVO();
            skuVO.setEcSkuId(ecSkuId);
            skuVO.setAutoStock("y");
            List<SkuVO> skuVOResult = itemService.findByWhere(skuVO);
            if (skuVOResult.size() == 0) {
                logger.info("平台商品[ID：" + ecSkuId + "]的库存同步已关闭");
                returnMessage = "平台商品[ID：" + ecSkuId + "]的库存同步已关闭";
            } else {
                ShopStorVO shopStorVO = new ShopStorVO();
                shopStorVO.setStorId(storageId);
                shopStorVO.setShopId(shopId);
                shopStorVO.setIsSyncStock(YesNoConst.YES);
                List<ShopStorVO> shopStorList = shopStorService.getShopStorByCondition(shopStorVO);
                if (shopStorList.size() == 0) {
                    logger.info("仓库[" + storageId + "]向店铺[" + shopId + "]推送库存的开关已关闭");
                    returnMessage = "仓库[" + storageId + "]向店铺[" + shopId + "]推送库存的开关已关闭";
                }
            }
        }
        return returnMessage;
    }

    /**
     * caculateStock:计算推送数 输入：项目ID，商店ID，商品ID和库存ID计算. <br/>
     *
     * @author zhanghao
     * @param projectId
     *            项目ID
     * @param shopId
     *            商品ID
     * @param skuId
     *            商品ID
     * @param storageId
     *            仓库ID
     * @param fmla
     *            库存公式
     * @return 返回计算结果的整数字符串
     * @throws Exception
     * @since JDK 1.6
     */
    @Override
    public String caculateStock(String projectId, String shopId, String skuId, String storageId, StockFmla fmla) throws Exception {
        String returnValue = "";
        // 获取商品在仓库中的库存相关数据
//        SkuStockVO skuStockVO = new SkuStockVO();
//        skuStockVO.setSkuId(skuId);
        String entId = fmla.getEntId();
        if (!StringUtils.isNotEmpty(entId)) {
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String key = (String) currentUser.getEnterpriseMap().keySet().toArray()[0];
            entId = currentUser.getEnterpriseMap().get(key);
        }
//        skuStockVO.setEntId(entId);
//        skuStockVO.setStorId(storageId);
//        List<SkuStock> skuStockList = goodsService.getSkuStockList(skuStockVO);
        
        StockVO stockVO = new StockVO();
        stockVO.setSkuId(skuId);
        stockVO.setEntId(entId);
        stockVO.setStorId(storageId);
        stockVO.setPrjId(projectId);
        PageInfo<StockVO> resultPagedStock = stockService.queryStockList(1, Integer.MAX_VALUE, stockVO);
        List<StockVO> skuStocklist = resultPagedStock.getList();
        if (skuStocklist.size() == 0) {
            return ""; // 如果仓库库不存在，返回此信息
        }

        // 根据库存公式计算实际库存数
        IStockCaculator felCaculator = new FelBasedStockCaculator();
        Map<String, Integer> paramMap = new HashMap<String, Integer>();
        BigDecimal caculateResult = new BigDecimal("0");
        String tempResult = "";
        // 本地数计算
        if ("local".equals(fmla.getStockValMode())) {
            for (StockVO skuStock : skuStocklist) {
                // 如果库存数是本地计算，就将库存数减去逻辑出库数
                paramMap.put("库存数", skuStock.getStockQty()-skuStock.getLogicStockoutQty());
                paramMap.put("在途数", skuStock.getOnwayQty());
                paramMap.put("已分派", skuStock.getAllotQty());
                paramMap.put("未分派", stockService.getUnallotQty(entId, skuId, storageId));
//                paramMap.put("未付款", ecTradeService.getUnpayQty(shopId, skuId));
                paramMap.put("预留数", skuStock.getReserveQty());
                paramMap.put("冻结数", skuStock.getFreezeQty());
                tempResult = felCaculator.caculateResult(fmla.getFormula(), paramMap);
                if (StringUtils.isNotEmpty(tempResult) && StringUtils.isNumeric(tempResult)) {
                    caculateResult = caculateResult.add(new BigDecimal(tempResult));
                } else {
                    caculateResult = new BigDecimal("0");
                    break;
                }
            }
        } else {
            // 第三方数计算
            for (StockVO skuStock : skuStocklist) {
                paramMap.put("库存数", skuStock.getSellCount());
                paramMap.put("在途数", skuStock.getOnwayQty());
                paramMap.put("已分派", skuStock.getAllotQty());
                paramMap.put("未分派", stockService.getUnallotQty(entId, skuId, storageId));
//                paramMap.put("未付款", ecTradeService.getUnpayQty(shopId, skuId));
                paramMap.put("预留数", skuStock.getReserveQty());
                paramMap.put("冻结数", skuStock.getFreezeQty());
                tempResult = felCaculator.caculateResult(fmla.getFormula(), paramMap);
                if (StringUtils.isNotEmpty(tempResult) && StringUtils.isNumeric(tempResult)) {
                    caculateResult = caculateResult.add(new BigDecimal(tempResult));
                } else {
                    caculateResult = new BigDecimal("0");
                    break;
                }
            }
        }

        BigDecimal result = new BigDecimal(0);
        // 步骤4 根据项目下仓库和店铺获取推送比例，计算商品的最终推送数
        BigDecimal pushRatio = new BigDecimal("0");
        // 店铺推送数
        StockFmlaRatioSkuVO skuFmlaRatioSkuVO = new StockFmlaRatioSkuVO();
        skuFmlaRatioSkuVO.setPrjId(projectId);
        skuFmlaRatioSkuVO.setSkuId(skuId);
        skuFmlaRatioSkuVO.setStorId(storageId);
        skuFmlaRatioSkuVO.setEntId(entId);
        skuFmlaRatioSkuVO.setShopId(shopId);
        List<StockFmlaRatioSkuVO> skuRatioListResult = stockPushRatioSkuDAO.selectBySelectiveValue(skuFmlaRatioSkuVO);
        if (skuRatioListResult.size() > 0) {
            // 按照商品推送比例计算推送数
            pushRatio = skuRatioListResult.get(0).getRatio();
        } else {
            // 按照仓库推送比例计算推送数
            StockFmlaRatioStorageVO stockFmlaRatioStorageVO = new StockFmlaRatioStorageVO();
            stockFmlaRatioStorageVO.setPrjId(projectId);
            stockFmlaRatioStorageVO.setStorId(storageId);
            stockFmlaRatioStorageVO.setShopId(shopId);
            stockFmlaRatioStorageVO.setEntId(entId);
            // 仓库推送数
            List<StockFmlaRatioStorage> storageRatioList = stockFmlaRatioStorageDAO.selectBySelectiveValue(stockFmlaRatioStorageVO);

            if (storageRatioList.size() > 0) {
                pushRatio = storageRatioList.get(0).getRatio(); // 如果有比例，则按照比例计算
            } else {
                return "-1"; // 没有设置推送比例时，返回-1
            }
        }
        // 计算结果
        result = pushRatio.multiply(caculateResult).divide(new BigDecimal("100"));
        returnValue = String.valueOf(result.intValue());
        logger.info("本次计算返回结果：" + returnValue);
        return returnValue;
    }

    private int getRandom() {
        java.util.Random random = new java.util.Random();// 定义随机类
        int result = random.nextInt(100);// 返回[0,10)集合中的整数，注意不包括10
        return result + 1;
    }

    /**
     * 方法复写 获取已经设置过库存推送比例的商品列表.
     * 
     * @throws Exception
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#getDistinctSetSkuList(int,
     *      int, cn.rkylin.oms.system.stockpush.vo.StockFmlaRatioSkuVO)
     */
    @Override
    public List<StockFmlaRatioSkuVO> getDistinctSetSkuList(int page, int length, StockFmlaRatioSkuVO stockFmlaRatioSkuVO) throws Exception {
        return stockPushRatioSkuDAO.getDistinckSetSku(page, length, stockFmlaRatioSkuVO);
    }

    /**
     * 方法复写 根据查询条件获取商品的库存推送比例.
     * 
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#getStockFmlaRatioSkuList(cn.rkylin.oms.system.stockpush.vo.StockFmlaRatioSkuVO)
     */
    @Override
    public List<StockFmlaRatioSkuVO> getStockFmlaRatioSkuList(StockFmlaRatioSkuVO stockFmlaRatioSkuVO) throws Exception {
        return stockPushRatioSkuDAO.selectBySelectiveValue(stockFmlaRatioSkuVO);
    }

    /**
     * 方法复写 保存商品的库存推送比例.
     * 
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#saveSkuRatio(java.util.List)
     */
    @Override
    public int saveSkuRatio(List<StockFmlaRatioSkuVO> skuRatioList) throws Exception {
        int returnValue = 0;
        Date now = new Date();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();

        for (StockFmlaRatioSkuVO stockFmlaRatioSkuVO : skuRatioList) {
            StockFmlaRatioSku record = new StockFmlaRatioSku();
            BeanUtils.copyProperties(stockFmlaRatioSkuVO,record);
            if ("y".equalsIgnoreCase(stockFmlaRatioSkuVO.getIsUpdate())) {
                record.setUpdateTime(now);
                // 如果推送比例是0，就删除这条
                if (record.getRatio().intValue() == 0) {
                    record.setDeleted("y");
                }
                returnValue = stockPushRatioSkuDAO.updateByPrimaryKeySelective(record);
            } else {
                String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
                // 新增记录
                record.setCreateTime(now);
                record.setUpdateTime(now);
                record.setDeleted("n");
                String key = (String) currentUser.getEnterpriseMap().keySet().toArray()[0];
                record.setEntId(key);
                record.setRatioId(uuid);
                // 如果推送比例不是0，才执行新增
                if (record.getRatio().intValue() != 0) {
                    stockPushRatioSkuDAO.insert(record);
                }
            }
        }
        return returnValue;
    }

    /**
     * 方法复写 删除商品的库存推送比例.
     * 
     * @see cn.rkylin.oms.system.stockpush.service.IStockPushService#deleteSkuRatio(cn.rkylin.oms.system.stockpush.vo.StockFmlaRatioSkuVO)
     */
    @Override
    public int deleteSkuRatio(StockFmlaRatioSkuVO stockFmlaRatioSkuVO) throws Exception {
        stockFmlaRatioSkuVO.setDeleted("y");
        return stockPushRatioSkuDAO.updateByPrimaryKeySelective(stockFmlaRatioSkuVO);
    }

    @Override
    public void deleteProjectSets(String projectId) throws Exception {
        StockFmla record = new StockFmla();
        record.setPrjId(projectId);
        record.setDeleted("y");
        // 删除库存公式
        stockFmlaDAO.updateByPrimaryKeySelective(record);
        // 删除仓库推送比例
        StockFmlaRatioStorage record4Storage = new StockFmlaRatioStorage();
        record4Storage.setPrjId(projectId);
        record4Storage.setDeleted("y");
        stockFmlaRatioStorageDAO.updateByPrimaryKeySelective(record4Storage);
        StockFmlaRatioSku record4Sku = new StockFmlaRatioSku();
        // 删除商品推送比例
        record4Sku.setPrjId(projectId);
        record4Sku.setDeleted("y");
        stockPushRatioSkuDAO.updateByPrimaryKeySelective(record4Sku);

    }

}
